import os
import sys
from config.LoadConfig import get_config


def chunk_list_into_chunks(data_list: list, chunk_size):
    return [data_list[i:i + chunk_size] for i in range(0, len(data_list), chunk_size)]


def base_work_dir():
    # server config
    __system_conf = get_config("system")
    __base_work_dir = os.path.join(__system_conf['work_dir'], __system_conf['server_name'])
    if not os.path.exists(__base_work_dir):
        os.makedirs(__base_work_dir)
    return __base_work_dir


def get_executable_path(execute_file: str = None):
    """获取项目文件执行路径"""
    if getattr(sys, 'frozen', False):
        # 如果程序被打包成了单文件
        return os.path.dirname(sys.executable)
    else:
        # 如果程序是从源代码直接运行
        if execute_file:
            return os.path.dirname(execute_file)
        else:
            return os.path.dirname(__file__)


def get_sqlite_db_path():
    """获取数据库文件路径"""
    return os.path.join(base_work_dir(), "db", "server.db")


def get_runtime_env_device():
    """获取运行环境（向后兼容）"""
    system_conf = get_config("system")
    runtime_env = system_conf['runtime_env']
    if runtime_env is None:
        device = 'cpu'
    else:
        device = 'cuda' if runtime_env == 'gpu' else runtime_env
    return device


def get_clip_device():
    """获取CLIP模型设备配置"""
    system_conf = get_config("system")
    clip_device = system_conf.get('clip_device', system_conf.get('runtime_env', 'cpu'))
    return 'cuda' if clip_device == 'gpu' else clip_device


def get_ocr_device():
    """获取OCR模型设备配置"""
    system_conf = get_config("system")
    ocr_device = system_conf.get('ocr_device', system_conf.get('runtime_env', 'cpu'))
    return 'cuda' if ocr_device == 'gpu' else ocr_device


def get_classify_model_device():
    """获取分类模型设备配置"""
    system_conf = get_config("system")
    classify_device = system_conf.get('classify_model_device', system_conf.get('runtime_env', 'cpu'))
    return 'gpu' if classify_device == 'gpu' else 'cpu'  # 分类模型使用gpu标识而不是cuda



def get_mysql_config():
    """获取MySQL数据库配置"""
    __system_conf = get_config("mysql")
    return {
        'host': __system_conf.get('host', 'localhost'),
        'port': int(__system_conf.get('port', 3306)),
        'user': __system_conf.get('user', 'root'),
        'password': __system_conf.get('password', ''),
        'database': __system_conf.get('database', 'ai_img_ocr')
    }